/**
 * @file http_server.cpp
 * @brief HTTP服务器实现
 */

#include "http_server.h"
#include "request_handler.h"
#include "logger.hpp"
#include <workflow/HttpUtil.h>

/**
 * @brief 构造函数
 */
HttpServer::HttpServer(int port) : port_(port)  
{
    server_ = std::make_unique<WFHttpServer>(process);
}

/**
 * @brief 析构函数
 */
HttpServer::~HttpServer() 
{
    stop();
}

/**
 * @brief 启动服务器
 */
bool HttpServer::start() 
{
    // 启动服务器
    if (server_->start(port_) == 0) 
    {
        Log::GetLogger("asynclogger")->Info("HTTP服务器启动成功，端口: %d", port_);
        return true;
    } 
    else 
    {
        Log::GetLogger("asynclogger")->Info("HTTP服务器启动失败");
        return false;
    }
}

/**
 * @brief 停止服务器
 */
void HttpServer::stop() 
{
    if (server_) 
    {
        server_->stop();
        Log::GetLogger("asynclogger")->Info("HTTP服务器已停止");
    }
}

/**
 * @brief 通用HTTP处理函数
 */
void HttpServer::process(WFHttpTask* task) 
{
    protocol::HttpRequest* req = task->get_req();
    protocol::HttpResponse* resp = task->get_resp();
    
    // 设置CORS头部
    resp->add_header_pair("Access-Control-Allow-Origin", "*");
    resp->add_header_pair("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    resp->add_header_pair("Access-Control-Allow-Headers", "Content-Type");
    
    // 处理OPTIONS预检请求
    if (strcmp(req->get_method(), "OPTIONS") == 0) 
    {
        resp->set_status_code("200");
        resp->set_reason_phrase("OK");
        return;
    }
    
    // 获取请求路径
    const char* uri = req->get_request_uri();
    std::string path(uri);
    
    // 移除查询参数
    size_t pos = path.find('?');
    if (pos != std::string::npos) 
    {
        path = path.substr(0, pos);
    }
    
    Log::GetLogger("asynclogger")->Info("处理请求: %s %s", req->get_method(), path.c_str());
    
    try 
    {
        // 路由分发
        if (path == "/" || path == "/index.html") 
        {
            RequestHandler::handleIndex(task);
        } 
        else if (path == "/upload") 
        {
            RequestHandler::handleUpload(task);
        } 
        else if (path.find("/download/") == 0) 
        {
            RequestHandler::handleDownload(task);
        } 
        else if (path.find("/info/") == 0) 
        {
            RequestHandler::handleFileInfo(task);
        } 
        else if (path.find("/static/") == 0) 
        {
            // 处理静态文件请求
            RequestHandler::handleStaticFile(task);
        } 
        else 
        {
            // 404 Not Found
            resp->set_status_code("404");
            resp->set_reason_phrase("Not Found");
            resp->append_output_body("<html><body><h1>404 Not Found</h1></body></html>");
        }
    } 
    catch (const std::exception& e) 
    {
        Log::GetLogger("asynclogger")->Info("处理请求异常: %s", e.what());
        
        // 500 Internal Server Error
        resp->set_status_code("500");
        resp->set_reason_phrase("Internal Server Error");
        resp->append_output_body("<html><body><h1>500 Internal Server Error</h1></body></html>");
    }
} 